/*
 * @Description: 服务调用loading
    options:{
        target:element | string dom元素或者类名
        title:string  loading文案
        background:string  loading背景色
    }
 * @Autor: 人生
 * @Date: 2020-09-28 16:44:22
 * @,@LastEditors: ,: 人生
 */
import { Spin } from 'ant-design-vue';
import Vue from 'vue';

const Mask = Vue.extend(Spin);

// 在考虑是否需要单例模式，看具体使用情况在修改
// 返回loadingService服务状态的实例  Loading.service()方式调用
export const Loading = (() => {
  const Service = function () {
    let div;
    let loadingMask;
    let container;
    this.service = function (options = {}) {
      const node = document.getElementsByClassName('ldx-axios-loading');
      if (node.length > 0) return this;
      const { target, title, background } = options;
      if (typeof target === 'string') {
        container = document.querySelector(target);
      } else {
        container = target;
      }
      container.style.position = 'relative';
      div = document.createElement('div');
      div.setAttribute('class', 'ldx-axios-loading');
      // div.style.position = "absolute";
      div.style.position = 'fixed';
      div.style.left = 0;
      div.style.right = 0;
      div.style.top = 0;
      div.style.bottom = 0;
      div.style.display = 'flex';
      div.style.alignItems = 'center';
      div.style.justifyContent = 'center';
      div.style.background = 'rgba(238, 238, 238,0.6)';
      div.style.zIndex = '99';
      if (background) div.style.background = background;
      const child = document.createElement('div');
      div.appendChild(child);
      container.appendChild(div);
      loadingMask = new Mask();
      loadingMask.spinning = true;
      if (title) loadingMask.tip = title;
      loadingMask.$mount(child);
      return this;
    };
    this.close = function () {
      const node = document.getElementsByClassName('ldx-axios-loading');
      if (node.length > 0) {
        loadingMask.spinning = false;
        container.removeChild(node[0]);
      }
    };
  };
  return new Service();
})();
